package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌用户端校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    /**
     * 用户端校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        try {
            //校验令牌
            log.info("[jwt校验] 校验开始");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);  //运行该行代码没有抛出异常,就说明校验通过
            log.info("[jwt校验] 校验通过");
            //从token中获取当前用户id,放到当前线程的一个局部变量中(ThreadLocal)
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            BaseContext.setCurrentId(userId);
            //放行
            return true;
        } catch (Exception e) {
            //检验不通过
            log.info("[jwt校验] 校验不通过");
            response.setStatus(401);    //响应401状态码
            return false;

        }
    }
}
